//
//  JZSpotlightTool.m
//  JFTwxsd
//
//  Created by Peter on 2018/5/28.
//  Copyright © 2018年 junfeiweiyejiaoyujituan. All rights reserved.
//

#import "JZSpotlightTool.h"
#import "AppDelegate.h"

@interface JZSpotlightTool ()

/// 标题
@property (strong, nonatomic) NSMutableArray *spotlightTitleArr;
/// 关键字
@property (strong, nonatomic) NSMutableArray *spotlightKeywordsArr;
/// 描述
@property (copy, nonatomic) NSMutableArray *spotlightDescArr;
/// 图标
@property (strong, nonatomic) NSMutableArray *spotlightPhotoArr;
///信息
@property (strong, nonatomic) NSMutableArray *spotlightUserInfoArr;
///动作
@property (copy, nonatomic) callback spotlightActivity;

@end

@implementation JZSpotlightTool

#pragma mark --------懒加载

- (NSMutableArray *)spotlightTitleArr {
    if (_spotlightTitleArr == nil) {
        _spotlightTitleArr = [NSMutableArray array];
    }
    return _spotlightTitleArr;
}

- (NSMutableArray *)spotlightDescArr {
    if (_spotlightDescArr == nil) {
        _spotlightDescArr = [NSMutableArray array];
    }
    return _spotlightDescArr;
}

- (NSMutableArray *)spotlightKeywordsArr {
    if (_spotlightKeywordsArr == nil) {
        _spotlightKeywordsArr = [NSMutableArray array];
    }
    return _spotlightKeywordsArr;
}

- (NSMutableArray *)spotlightPhotoArr {
    if (_spotlightPhotoArr == nil) {
        _spotlightPhotoArr = [NSMutableArray array];
    }
    return _spotlightPhotoArr;
}

- (NSMutableArray *)spotlightUserInfoArr {
    if (_spotlightUserInfoArr == nil) {
        _spotlightUserInfoArr = [NSMutableArray array];
    }
    return _spotlightUserInfoArr;
}

#pragma mark --------链式语法

- (SpotlightText)title {
    return ^(NSArray *title) {
        self.spotlightTitleArr = [title mutableCopy];
        return self;
    };
}

- (SpotlightText)descp {
    return ^(NSArray *descp) {
        self.spotlightDescArr = [descp mutableCopy];
        return self;
    };
}

- (SpotlightKeywords)keywords {
    return ^(NSArray *keyArr) {
        self.spotlightKeywordsArr = [keyArr mutableCopy];
        return self;
    };
}

- (SpotlightImage)image {
    return ^(NSArray *imageData) {
        self.spotlightPhotoArr = [imageData mutableCopy];
        return self;
    };
}

- (SpotlightClosure)userActivity {
    return ^(callback activity) {
        self.spotlightActivity = activity;
        return self;
    };
}

- (SpotlightText)userInfo {
    return ^(NSArray *userInfo) {
        self.spotlightUserInfoArr = [userInfo mutableCopy];
        return self;
    };
}

#pragma mark --------初始化方法

- (void)makeSpotlight {
    if (self.spotlightTitleArr.count == 0) {
        return ;
    }
    if (@available(iOS 9.0, *)) {
        NSMutableArray *tmpItemArr = [NSMutableArray array];
        for (int idx = 0; idx < self.spotlightTitleArr.count; idx++) {
            CSSearchableItemAttributeSet *attributeSet = [[CSSearchableItemAttributeSet alloc] initWithItemContentType:(NSString *)kUTTypeImage];
            attributeSet.title = self.spotlightTitleArr[idx];
            attributeSet.keywords = self.spotlightKeywordsArr[idx];
            attributeSet.contentDescription = self.spotlightDescArr[idx];
            attributeSet.thumbnailData = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.spotlightPhotoArr[idx]]];
            /// spotlightInfo 可以作为一些数据传递给接受的地方
            /// domainId      id,通过这个id来判断是哪个spotlight
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self.spotlightUserInfoArr[idx] options:NSJSONWritingPrettyPrinted error:nil];
//            NSString *jsonStr = [NSString stringWithData:jsonData encoding:NSUTF8StringEncoding];
            NSString *jsonStr = @"";
            CSSearchableItem *item = [[CSSearchableItem alloc] initWithUniqueIdentifier:jsonStr domainIdentifier:jsonStr attributeSet:attributeSet];
            [tmpItemArr addObject:item];
        }
        
        [[CSSearchableIndex defaultSearchableIndex] indexSearchableItems:tmpItemArr completionHandler:^(NSError * error) {
            if (error) {
                NSLog(@"indexSearchableItems Error:%@",error.localizedDescription);
            }
        }];
    }
}

- (void)deleteAllSpotlight {
    if (@available(iOS 9.0, *)) {
        [[CSSearchableIndex defaultSearchableIndex] deleteAllSearchableItemsWithCompletionHandler:^(NSError * _Nullable error) {
            if (error) {
                NSLog(@"删除spotlight失败,Error:%@",error.localizedDescription);
            }
        }];
    } else {
        // Fallback on earlier versions
    }
}

@end

@implementation AppDelegate (JZSpotlightTool)

//+ (void)load {
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        Method method1 = class_getInstanceMethod([AppDelegate class], @selector(application:continueUserActivity:restorationHandler:));
//
//        Method method2 = class_getInstanceMethod([AppDelegate class], @selector(JZ_application:continueUserActivity:restorationHandler:));
//        method_exchangeImplementations(method1, method2);
//    });
//}

- (BOOL)JZ_application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler {
    [self JZ_application:application continueUserActivity:userActivity restorationHandler:restorationHandler];
    if (@available(iOS 9.0, *)) {
        if ([[userActivity activityType] isEqualToString:CSSearchableItemActionType]) {
            NSString *uniqueIdentifier = [userActivity.userInfo objectForKey:CSSearchableItemActivityIdentifier];
            callback  back = JZSpotlightTool.shared.spotlightActivity;
            !back ?: back(userActivity.userInfo);
        }
    }
    return YES;
}

@end

#pragma mark - 单例相关

static dispatch_once_t onceToken;
static JZSpotlightTool *instance;
@implementation JZSpotlightTool (Once)

+ (nonnull instancetype)shared {
    return [JZSpotlightTool new];
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    dispatch_once(&onceToken, ^{
        instance = [super allocWithZone:zone];
    });
    return instance;
}

- (instancetype)init {
    dispatch_once(&onceToken, ^{
        instance = [super init];
    });
    self = instance;
    return self;
}

- (id)copy {
    return self;
}

- (id)mutableCopy {
    return self;
}

@end
